package cc.mrbird.febs.accounting.controller;

import cc.mrbird.febs.accounting.entity.Project;
import cc.mrbird.febs.accounting.service.IExportService;
import cc.mrbird.febs.accounting.service.IProjectService;
import cc.mrbird.febs.accounting.service.impl.ProjectServiceImpl;
import cc.mrbird.febs.common.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Validated
@Controller
@RequestMapping("/export")
public class ExportController extends BaseController {

    @Resource
    private IExportService exportService;
    @Resource
    private IProjectService projectService;

    @GetMapping("/exportIncome")
    // 获取到和前端相对应的detailCost/exportIncome params中params所对应的各字段名字，year和params中的name:year是同一个
    public void download(HttpServletResponse response, @RequestParam("year") String year, @RequestParam("month") String month,
                         @RequestParam("projectId") String projectId, @RequestParam("choice") String choice,
                         @RequestParam("orderByPro") Integer orderByPro) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 将从params中获取到的month以数组的形式存入字符数组months中
        String[] months = month.split(",");
        // 创建一个空字符数组 yearMonths
        List<String> yearMonths = new ArrayList<>();
        // 使yearMonths里面存的是规范为yy-mm的年月（如2022-04）
        for (String e : months) {
            if (Integer.parseInt(e) < 10) {
                yearMonths.add(year + "-0" + e);
            } else {
                yearMonths.add(year + "-" + e);
            }
        }
        List<String> projectIds = Arrays.asList(projectId.split(","));
        List<Project> projects_tmp = this.projectService.getProjectByIds(projectIds);
        List<Project> projects = new ArrayList<>();
        // 将项目按照选择的顺讯排序
        if (orderByPro == 1) {
            for (String id : projectIds) {
                projects.add(projects_tmp.stream().filter(e->e.getId().toString().equals(id)).findFirst().orElse(null));
            }
        } else {
            projects = projects_tmp;
        }

        if (Integer.parseInt(choice) == 1||Integer.parseInt(choice) == 2) {
            exportService.queryIncomeForExcel(projects, year, yearMonths, workbook, choice);
        } else if (Integer.parseInt(choice)==0){
            exportService.exportBusinessIncome(projects, projectIds, year, yearMonths, workbook);
        }
        String filePath = year.concat("未开票收入统计").concat(".xlsx");
        response.reset();//清除buffer缓存
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(filePath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));// 定义文件名
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", " 0");

        try {
            OutputStream output;
            output = response.getOutputStream();
            BufferedOutputStream bufferOutput = new BufferedOutputStream(output);
            bufferOutput.flush();
            workbook.write(bufferOutput);
            bufferOutput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
